#include "config.h"
#include "WebViewManager.h"

#include "AXObjectCache.h"
#include "ImageSource.h"
#include "InitializeLogging.h"
#include "JavaScriptCore/runtime/InitializeThreading.h"
#include "Logging.h"
#include "MemoryCache.h"
#include "PageGroup.h"
#include "PlatformStrategiesManx.h"
#include "ResourceHandleManager.h"
#include "WebViewPrivate.h"

namespace WebKit {

void WebViewManager::deleteAllCookies()
{
    WebCore::ResourceHandleManager::sharedInstance()->deleteAllCookies();
}

void WebViewManager::setCookies(const char* url, const char* cookie)
{
    WTF::String cookieStr = cookie;
    WebCore::KURL kurl(WebCore::ParsedURLString, url);
    WTF::String value = cookie;
    WebCore::ResourceHandleManager::sharedInstance()->setCookies(kurl, value);
}

void WebViewManager::initWebCore()
{
    JSC::initializeThreading();
    WTF::initializeMainThread();

#if !LOG_DISABLED
    WebCore::initializeLoggingChannelsIfNecessary();
#endif
    PlatformStrategiesManx::initialize();

    WebCore::PageGroup::setShouldTrackVisitedLinks(true);

    WebCore::AXObjectCache::enableAccessibility();
    WebCore::AXObjectCache::accessibilityEnhancedUserInterfaceEnabled();

    // Set memory cache capacity. Note that MemoryCache instance is not 
    // accessible before initWebCore()
    const char* cacheCapacityString = getenv("MEMORY_CACHE_CAPACITY");
    if (cacheCapacityString) {
        // Get capacity size in MiB.
        int capacity = atoi(cacheCapacityString);
        if (capacity >= 8 && capacity <= 128) {
            capacity *= 1024 * 1024;
            WebCore::memoryCache()->setCapacities(0, capacity, capacity);
        }
    }

#if ENABLE(IMAGE_DECODER_DOWN_SAMPLING)
    // Set image size cap.
    unsigned maxPixelsPerDecodedImage = 0; // 0 means unlimited.
    const char* maxPixelsPerDecodedImageString = getenv("MAX_PIXELS_PER_DECODED_IMAGE");
    if (maxPixelsPerDecodedImageString)
        maxPixelsPerDecodedImage = atoi(maxPixelsPerDecodedImageString);
    WebCore::ImageSource::setMaxPixelsPerDecodedImage(maxPixelsPerDecodedImage);
#endif

    WebCore::ResourceHandleManager::setup();
}

void WebViewManager::exitWebCore()
{
    // we need to explictly do some cleanup of static members in WebCore
    WebCore::ResourceHandleManager::cleanup();
#if 0
    WebCore::JSDOMWindowBase::cleanup();
#endif
}

} // namespace WebKit
